package com.aluvfy.bank.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @author: aluvfy
 * @description: MyBatis工具类
 * @date: 2024/10/31 10:16
 */
public class SqlSessionUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(Resources.getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private SqlSessionUtil() {
    }

    //全局的，服务器级别的，一个服务器当中定义一个即可。
    private static ThreadLocal<SqlSession> local = new ThreadLocal<>();

    public static SqlSession openSession(){
        SqlSession sqlSession = local.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            //将sqlSession对象绑定到当前线程
            local.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 关闭sqlSession(从当前线程中移除sqlSession对象)
     * @param sqlSession
     */
    public static void close(SqlSession sqlSession){
        if (sqlSession != null) {
            sqlSession.close();
            //注意移除sqlSession对象和当前线程的绑定关系
            //因为Tomcat服务器支持线程池，线程复用，所以线程池中的线程会一直存在，也就是说，用过的线程对象t1，可能下次还会使用这个t1线程
            local.remove();
        }
    }
}
